package com.suvel.study.controller;

import com.suvel.study.dao.TokenDao;
import com.suvel.study.pojo.User;
import com.suvel.study.service.TokenService;
import com.suvel.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import static com.suvel.study.contants.Contants.COOKIE_NAME;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TokenDao tokenDao;

    @GetMapping("/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable String email, @PathVariable String password, @PathVariable String code, HttpServletResponse response){
        boolean result = true;
        try{
            User registerUser = userService.register(email, password, code);
            if(registerUser != null){
                //生成token
                String token = tokenService.createTokenCookie(email);
                setCookie(response,token);
            }
            System.out.println("registerUser:" + registerUser);
        }catch (Exception ex){
            ex.printStackTrace();
            result = false;
        }
        return result;
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable String email){
        boolean result;
        try{
            result = userService.isRegistered(email);
        }catch (Exception ex){
            ex.printStackTrace();
            result = false;
        }
        return result;
    }

    @GetMapping("/login/{email}/{password}")
    public Boolean login(@PathVariable String email,@PathVariable String password,HttpServletResponse response){
        boolean result;
        try{
            result = userService.login(email,password);
            if(result){
                String token = tokenService.createTokenCookie(email);
                setCookie(response,token);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            result = false;
        }
        return result;
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token){
        String email = null;
        try {
            email = tokenService.findEmailByToken(token);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return email;
    }

    private void setCookie(HttpServletResponse response, String token) {
        Cookie tokenCookie = new Cookie(COOKIE_NAME,token);
        tokenCookie.setHttpOnly(false);
        tokenCookie.setPath("/");
        tokenCookie.setDomain("www.test.com");
        response.addCookie(tokenCookie);
    }
}
